package com.example.campsystem.controller;

import com.example.campsystem.entity.CustomApi;
import com.example.campsystem.entity.User;
import com.example.campsystem.service.UserService;
import com.example.campsystem.service.WechatService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
    private final WechatService wechatService;
    private final UserService userService;

    @PostMapping("/login/wechat/{code}")
    public ResponseEntity<CustomApi> loginWithWechat(@PathVariable String code, @RequestBody User user) {
        System.out.println(user.getNickname());
        CustomApi customApi = new CustomApi();
        try {
            User loggedInUser = wechatService.loginWithWechat(code, user);
            System.out.println(loggedInUser);
            customApi.setCode(200);
            customApi.setMsg("success");
            customApi.setData(loggedInUser);
        } catch (Exception e) {
            customApi.setCode(500);
            customApi.setMsg("登录失败：" + e.getMessage());
        }
        return new ResponseEntity<>(customApi, customApi.getCode() == 200 ? HttpStatus.OK : HttpStatus.INTERNAL_SERVER_ERROR);
    }
    //更新用户信息
    @PutMapping("/update")
    public ResponseEntity<CustomApi> updateUser(@RequestBody User user) {
        CustomApi customApi = new CustomApi();
        System.out.println(user);
        try {
            boolean isUpdated = userService.update(user);
            if (isUpdated) {
                customApi.setCode(200);
                customApi.setMsg("更新成功");
            } else {
                customApi.setCode(500);
                customApi.setMsg("更新失败");
            }
        } catch (Exception e) {
            customApi.setCode(500);
            customApi.setMsg("更新失败：" + e.getMessage());
        }
        return new ResponseEntity<>(customApi, customApi.getCode() == 200 ? HttpStatus.OK : HttpStatus.INTERNAL_SERVER_ERROR);
    }
}